package com.yzf.wisecoder.wisecoderservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yzf.wisecoder.wisecodercommon.utils.SecurityUtils;
import com.yzf.wisecoder.wisecodercommon.vo.request.ProjectUserReq;
import com.yzf.wisecoder.wisecodercommon.vo.request.UserReq;
import com.yzf.wisecoder.wisecoderservice.service.ProjectUserService;
import com.yzf.wisecoder.wisecoderstorage.mysql.dao.ProjectUserDao;
import com.yzf.wisecoder.wisecoderstorage.mysql.entity.ProjectUserEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author jianghuiyong
 * @email jianghuiyong@yunzhangfang.com
 * @date 2020-05-06 17:43:12
 */
@Service("projectUserService")
public class ProjectUserServiceImpl extends ServiceImpl<ProjectUserDao, ProjectUserEntity> implements ProjectUserService {

    @Override
    public boolean removeByProjectIds(List<Long> projectIds) {
        baseMapper.removeByProjectIds(projectIds);
        return true;
    }

    @Override
    public boolean saveProjectUser(ProjectUserReq projectUserReq) {
        List<ProjectUserEntity> list = Lists.newArrayList();
        for (UserReq userReq : projectUserReq.getUsers()) {
            ProjectUserEntity projectUserEntity = new ProjectUserEntity();
            projectUserEntity.setUserId(userReq.getUserId())
                    .setUserName(userReq.getUserName())
                    .setProjectId(projectUserReq.getProjectId())
                    .setTenantId(SecurityUtils.getTenantId())
                    .setCreator(SecurityUtils.getUserId())
                    .setRoleId(projectUserReq.getRoleId())
                    .setCreateTime(LocalDateTime.now());
            list.add(projectUserEntity);
        }
        saveBatch(list);
        return true;
    }

    @Override
    public boolean removeProjectUser(Long userId, Long projectId) {
        return remove(new QueryWrapper<ProjectUserEntity>().eq("user_id", userId).eq("project_id", projectId));
    }

    @Override
    public List<ProjectUserEntity> queryByRoleId(Long roleId, Long tenantId) {
        List<ProjectUserEntity> list = list(new QueryWrapper<ProjectUserEntity>().eq("role_id", roleId)
                .eq("tenant_id", tenantId));
        return list;
    }

    @Override
    public List<ProjectUserEntity> queryByProjectId(Long projectId, Long tenantId) {
        List<ProjectUserEntity> list = list(new QueryWrapper<ProjectUserEntity>()
                .eq("project_id", projectId)
                .eq("tenant_id", tenantId));
        return list;
    }
}